package com.zntg.schedule;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zntg.api.renGouShu.result.ResultModel;
import com.zntg.api.shuanglu.result.DownloadFileResult;
import com.zntg.api.uploadFileCreateContract.contants.YunHeTongApiContants;
import com.zntg.api.uploadFileCreateContract.param.HeTongDownLoadParam;
import com.zntg.api.uploadFileCreateContract.result.UploadFileCreateContract.UploadFileCreateContractJsonRootBean;
import com.zntg.bo.FundFeneSureBook;
import com.zntg.bo.SpciProdType3Bo;
import com.zntg.bo.TSpciProdBo;
import com.zntg.contants.FundFeneSureBookContants;
import com.zntg.entity.TSpciProdNewEntity;
import com.zntg.entity.TblobstorageNewEntity;
import com.zntg.mapper.crmdb.TblobtSorageMapper;
import com.zntg.mapper.odsdb.HangZhouWangHeMapper;
import com.zntg.mapper.odsdb.TSpciProdNewMapper;
import com.zntg.utils.*;
import com.zntg.utils.http.HttpIOUtil;
import com.zntg.utils.http.HttpRequestUtil;
import com.zntg.utils.poiTl.PoiTlUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description: 对应ods库T_SPCI_PROD_NEW这张表的SPCI_TYE = '3'的份额确认书生成功能
 * 采用word替换的方式，生成认购书
* @Author: zhengyunfei
* @Date: 2019/6/12  
* @time:13:34        
*/ 
@Component
public class NewTemplate3ScheduledTask {
    @Value("${server.port}")
    String port;
    /**电子签章生成路径*/
    @Value("${template.targetPath}")
    String targetPath;
    @Value("${template.sourcePath}")
    String sourcePath;//word模板存放路径
    private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(NewTemplate3ScheduledTask.class);

    /**
     * 每隔5秒执行, 单位：ms。
     */
  /*  @Scheduled(fixedRate = 5000)
    public void testFixRate() {
        System.out.println("我每隔5秒冒泡一次：" + dateFormat.format(new Date()));
        Logger.info("打印当前时间: {}.", dateFormat.format(new Date()));
    }*/

   //@Scheduled(cron = "0 0 1 * * ?")   //每天凌晨1点执行
   @Scheduled(cron = "0 0/5 * * * ?")    //每10分钟执行一次
   /*@Scheduled(fixedRate = 50000000)*/
    public void task3() {
        try {
            System.out.println("NewTemplate3ScheduledTask计划任务开始执行，规则5分钟1次，当前执行时间==="+ DateUtils.getCurrentDate());
            TblobtSorageMapper tblobtSorageMapper = ComponentFactory.getBean(TblobtSorageMapper.class);
            HangZhouWangHeMapper hangZhouWangHeMapper = ComponentFactory.getBean(HangZhouWangHeMapper.class);
            TSpciProdNewMapper tSpciProdMapper = ComponentFactory.getBean(TSpciProdNewMapper.class);
            //获取要生成的数据
            List<SpciProdType3Bo> list = hangZhouWangHeMapper.findNewAllList();
            Gson gson=new Gson();
            if(list.size()>0){
                System.out.println("ods库T_SPCI_PROD这张表的SPCI_TYE = '3'的份额确认书开始生成需要生成认购书的总数===================================="+list.size());
                for(int i=0;i<list.size();i++){
                    SpciProdType3Bo temleteBo=list.get(i);
                    String lMandatorId=temleteBo.getlMandatorId();//管理人ID
                    TSpciProdBo tSpciProdBo=new TSpciProdBo();
                    tSpciProdBo.setProdId(lMandatorId);
                    TSpciProdNewEntity tSpciProdEntity=tSpciProdMapper.findByBo(tSpciProdBo);
                    FundFeneSureBook fundFeneSureBook=SpciProdType3Bo.getFeneBook(temleteBo);
                    fundFeneSureBook.setSourcePath(tSpciProdEntity.getPurMod());
                    //根据产品编号查询生成的认购书或者追加书模板的名称，配置在T_SPCI_PROD表里面，此外需要将模板放在项目service_electronic_signatu的reresources下面
                    //查询crm附件序号
                    String cSubKeyId=temleteBo.getlBenserialNo();
                    fundFeneSureBook.setPkId(cSubKeyId);
                    String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
                    fundFeneSureBook.setlStorageid(lStorageid);
                    fundFeneSureBook.setCyType(FundFeneSureBookContants.SPCI_TYE_3);
                    fundFeneSureBook.setTargetPath(targetPath);
                    PoiTlUtil poiTlUtil=new PoiTlUtil();
                    Map<String,Object> dataMap=new HashMap<>();
                    String prodName=fundFeneSureBook.getProdNm();
                    dataMap.put("C_CUSTNAME",fundFeneSureBook.getUserName());//用户名称
                    dataMap.put("C_FUNDNAME",prodName);//产品名称
                    dataMap.put("CONTRACTID",fundFeneSureBook.getHtNo());//合同编号
                    dataMap.put("F_BALANCE",MoneyTool.formatTosepara(Double.parseDouble(fundFeneSureBook.getRgSmallMoney())));//小写金额千分符分隔
                    String bigMoney=fundFeneSureBook.getRgBigMoney();
                    if(""!=bigMoney&&null!=bigMoney){
                        double moneyDouble=Double.parseDouble(bigMoney);
                        String MONEY= MoneyTool.change(moneyDouble);
                        if(MONEY.contains("元整")){
                            MONEY=MONEY.replace("元整","");
                        }
                        if(MONEY.contains("万")){
                            MONEY=MONEY.replace("万","");
                        }
                        if(MONEY.contains("千")){
                            MONEY=MONEY.replace("千","仟");
                        }
                        dataMap.put("F_BALANCE_UPP",MONEY);//大写金额
                    }
                    dataMap.put("INT_DATE_Y",fundFeneSureBook.getIntDateY());//份额确认日 年
                    dataMap.put("INT_DATE_M",fundFeneSureBook.getIntDateM());//份额确认日 月
                    dataMap.put("INT_DATE_D",fundFeneSureBook.getIntDateD());//份额确认日 日
                    //基金成立日
                    dataMap.put("SET_DATE_Y", fundFeneSureBook.getFundCreateDateY());//基金成立日 年
                    dataMap.put("SET_DATE_M",fundFeneSureBook.getFundCreateDateM());//基金成立日 月
                    dataMap.put("SET_DATE_D", fundFeneSureBook.getFundCreateDateD());//基金成立日 日
                    //存续期限
                    dataMap.put("C_DEADLINE",fundFeneSureBook.getcDeadLine());
                    //确认书生成日，底部盖章日期，需要转换为大写
                    dataMap.put("CREATE_DATE_Y",fundFeneSureBook.getCreateDateYear());
                    dataMap.put("CREATE_DATE_M",fundFeneSureBook.getCreateDateMth());
                    dataMap.put("CREATE_DATE_D",fundFeneSureBook.getCreateDateDay());
                    //获取替换后模板生成路径
                    String l_storageid=fundFeneSureBook.getlStorageid();
                    String fileName=fundFeneSureBook.getFileName();
                    String docTemplatePath=sourcePath+"\\new\\"+fileName.replace(".pdf","")+".docx";
                    poiTlUtil.createTemplate(sourcePath+fundFeneSureBook.getSourcePath(),docTemplatePath,dataMap);
                    //将生成后的word转换为pdf
                    HttpIOUtil httpIOUtil=new HttpIOUtil();
                    String token=httpIOUtil.getLongToken(YunHeTongApiContants.AppID,YunHeTongApiContants.AppKey,"");
                    String uploadFileCreateContractResultJson= httpIOUtil.uploadFileCreateContract(token,docTemplatePath,prodName);
                    System.out.println("调用接口返回结果======"+uploadFileCreateContractResultJson);
                    UploadFileCreateContractJsonRootBean uploadFileCreateContractJsonRootBean= (UploadFileCreateContractJsonRootBean) gson.fromJson(uploadFileCreateContractResultJson,UploadFileCreateContractJsonRootBean.class);
                    long contractId=uploadFileCreateContractJsonRootBean.getData().getContractId();
                    //更改合同下载
                    String url= YunHeTongApiContants.DOWNLOAD_CONTRACT_API;//合同下载
                    String jsonParam="";
                    //将下载好的合同pdf存放到认购书响应的目录下
                    //获取当天日期
                    String today= DateUtil.getToDay();
                    String targetPath=fundFeneSureBook.getTargetPath();
                    String path=targetPath+today;
                    boolean flag=FileUtils.mkdir(path);
                    if(!flag){
                        path=path+"\\Tblobstorage";
                        flag=FileUtils.mkdir(path);
                    }else{
                        path=path+"\\Tblobstorage";
                    }
                    String lStorageId=l_storageid.substring(0,l_storageid.length()-1);
                    path=path+"\\"+lStorageId;
                    FileUtils.mkdir(path);
                    String createTofileName=l_storageid+"baccessory";
                    String createPath=path;
                    HeTongDownLoadParam heTongDownLoadParam=new HeTongDownLoadParam();
                    heTongDownLoadParam.setIdContent(contractId+"");
                    heTongDownLoadParam.setIdType("0");
                    jsonParam=gson.toJson(heTongDownLoadParam);
                    long fileSize=DownLoadContractHttpUtil.post(token,url,jsonParam,createPath+"\\",createTofileName);
                    String storId=fundFeneSureBook.getlStorageid();//上述sql的
                    //生成附件表到Crmku
                    TblobstorageNewEntity tblobstorageBo=new TblobstorageNewEntity();
                    tblobstorageBo.setlStorageid(storId+"");
                    String cSubkeyId=fundFeneSureBook.getPkId();
                    tblobstorageBo.setcSubkeyid(cSubkeyId);
                    tblobstorageBo.setcFilename(fileName);
                    tblobstorageBo.setlFilesize(fileSize+"");
                    tblobtSorageMapper.addFeiJingZhiLeiProd(tblobstorageBo);

                }
            }else{
               // System.out.println("我什么事都不用做，等待下次再说吧");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }
    }
    public String createSignFeiJingZhiProd(String  jsonData ){
        String resultJson="";
        try {
            System.out.println("根据word模板生成认购书参数="+jsonData);
            Gson gson=new Gson();
            List <FundFeneSureBook> list=gson.fromJson(jsonData,new TypeToken<List<FundFeneSureBook>>(){}.getType());
            List <FundFeneSureBook> result=new ArrayList<>();
            if(null!=list){
                for(int i=0;i<list.size();i++){
                    FundFeneSureBook fundFeneSureBook=list.get(i);
                    fundFeneSureBook.setTargetPath(targetPath);
                    PoiTlUtil poiTlUtil=new PoiTlUtil();
                    Map<String,Object> dataMap=new HashMap<>();
                    String prodName=fundFeneSureBook.getProdNm();
                    dataMap.put("C_CUSTNAME",fundFeneSureBook.getUserName());//用户名称
                    dataMap.put("C_FUNDNAME",prodName);//产品名称
                    dataMap.put("CONTRACTID",fundFeneSureBook.getHtNo());//合同编号
                    dataMap.put("F_BALANCE",MoneyTool.formatTosepara(Double.parseDouble(fundFeneSureBook.getRgSmallMoney())));//小写金额千分符分隔
                    String bigMoney=fundFeneSureBook.getRgBigMoney();
                    if(""!=bigMoney&&null!=bigMoney){
                        double moneyDouble=Double.parseDouble(bigMoney);
                        String MONEY= MoneyTool.change(moneyDouble);
                        if(MONEY.contains("元整")){
                            MONEY=MONEY.replace("元整","");
                        }
                        if(MONEY.contains("万")){
                            MONEY=MONEY.replace("万","");
                        }
                        if(MONEY.contains("千")){
                            MONEY=MONEY.replace("千","仟");
                        }
                        dataMap.put("F_BALANCE_UPP",MONEY);//大写金额
                    }
                    dataMap.put("INT_DATE_Y",fundFeneSureBook.getIntDateY());//份额确认日 年
                    dataMap.put("INT_DATE_M",fundFeneSureBook.getIntDateM());//份额确认日 月
                    dataMap.put("INT_DATE_D",fundFeneSureBook.getIntDateD());//份额确认日 日
                    //基金成立日
                    dataMap.put("SET_DATE_Y", fundFeneSureBook.getFundCreateDateY());//基金成立日 年
                    dataMap.put("SET_DATE_M",fundFeneSureBook.getFundCreateDateM());//基金成立日 月
                    dataMap.put("SET_DATE_D", fundFeneSureBook.getFundCreateDateD());//基金成立日 日
                    //存续期限
                    dataMap.put("C_DEADLINE",fundFeneSureBook.getcDeadLine());
                    //确认书生成日，底部盖章日期，需要转换为大写
                    dataMap.put("CREATE_DATE_Y",fundFeneSureBook.getCreateDateYear());
                    dataMap.put("CREATE_DATE_M",fundFeneSureBook.getCreateDateMth());
                    dataMap.put("CREATE_DATE_D",fundFeneSureBook.getCreateDateDay());
                    //获取替换后模板生成路径
                    String l_storageid=fundFeneSureBook.getlStorageid();
                    String docTemplatePath=sourcePath+"\\new\\"+fundFeneSureBook.getFileName().replace(".pdf","")+".docx";
                    poiTlUtil.createTemplate(sourcePath+fundFeneSureBook.getSourcePath(),docTemplatePath,dataMap);
                    //将生成后的word转换为pdf
                    HttpIOUtil httpIOUtil=new HttpIOUtil();
                    String token=httpIOUtil.getLongToken(YunHeTongApiContants.AppID,YunHeTongApiContants.AppKey,"");
                    String uploadFileCreateContractResultJson= httpIOUtil.uploadFileCreateContract(token,docTemplatePath,prodName);
                    System.out.println("调用接口返回结果======"+uploadFileCreateContractResultJson);
                    UploadFileCreateContractJsonRootBean uploadFileCreateContractJsonRootBean= (UploadFileCreateContractJsonRootBean) gson.fromJson(uploadFileCreateContractResultJson,UploadFileCreateContractJsonRootBean.class);
                    long contractId=uploadFileCreateContractJsonRootBean.getData().getContractId();
                    //根据合同id下载合同
                    String url =YunHeTongApiContants.DOWNLOAD_CONTRACT;
                    String para = "idContent="+contractId;
                    String downLoadResultJsonStr= HttpRequestUtil.sendPost(url,para,false);
                   ResultModel downLoadResultModel=gson.fromJson(downLoadResultJsonStr,ResultModel.class);
                    System.out.println("合同下载返回结果========"+downLoadResultModel.toString());
                    Object data=downLoadResultModel.getData();
                    //将下载好的合同pdf存放到认购书响应的目录下
                    //获取当天日期
                    String today= DateUtil.getToDay();

                    String targetPath=fundFeneSureBook.getTargetPath();
                    String path=targetPath+today;
                    boolean flag=FileUtils.mkdir(path);
                    if(!flag){
                        path=path+"\\Tblobstorage";
                        //   file=new File(path);
                        flag=FileUtils.mkdir(path);
                    }else{
                        path=path+"\\Tblobstorage";
                    }
                    String lStorageId=l_storageid.substring(0,l_storageid.length()-1);
                    path=path+"\\"+lStorageId;
                    FileUtils.mkdir(path);
                    String createTofileName=l_storageid+"baccessory";
                    String createPath=path;
                    DownloadFileResult downloadFileResult=DownloadPdf.downLoadServerFileToLocal(data.toString(),createTofileName,createPath);
                    fundFeneSureBook.setFileSize(downloadFileResult.getFileSize());
                    result.add(fundFeneSureBook);
                }
                resultJson=gson.toJson(result);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return resultJson;
    }
}

